<?php

/**
 * [WeEngine System] Copyright (c) 2013 WE7.CC
 * User: fanyk
 * Date: 2017/12/10
 * Time: 14:46.
 */

include IA_ROOT . '/addons/bh_rising/lib/function.php';
include IA_ROOT . '/addons/bh_rising/lib/WxpayAPI_php_v3/WxpayAPI_php_v3.php';
include IA_ROOT . '/addons/bh_rising/lib/WXBizDataCrypt.php';

include 'controller/common.php';
include 'model/rising.mod.php';
include 'lib/Wxadoc.php';
include 'lib/Qqadoc.php';

class bh_risingModuleWxapp extends WeModuleWxapp {


    public $action = '';
    public $contr = '';

    public function __construct() {
        global $_W;
        define('UNIACID', $_W['uniacid']);
    }




    public function doPageDistribute()
    {
        global $_GPC;
        $this->action = $_GPC['action'] ? : 'index';
        $this->contr = $_GPC['contr'] ? : 'index';

        include_once "controller/{$this->contr}.php";

        $c = new $this->contr;

        if (method_exists($c, $this->action)) {
            $c->{$this->action}();
        }
    }


    public function createUrl($do, $query = array())
    {
        global $_W;
        $url = $_W['siteroot'] . "/index.php?i=" . UNIACID . "&from=wxapp&c=entry&a=wxapp&do={$do}&m=bh_rising&";
        if ($query) {
            $queryString = http_build_query($query, '', '&');
            $url .= $queryString;
        }
        return $url;
    }






    public function doPageQuestionList()
    {
        define('IN_SYS', true); //入口常量定义
        $table = prefix('question');
        $list = p_getall('question', array(), array(), '', 'sort DESC, id DESC');
        //$where = "uniacid = {$this->w['uniacid']}";
        //$list = pdo_fetchall('SELECT * FROM '.$table." WHERE {$where} ORDER BY sort DESC,id DESC ");
        $product_name = getConfig('xcx_title', '奇趣礼物');
        include $this->template('question_list');
    }



    /**
     * 计划任务
     */
    public function doPageCrontab()
    {

        global $_W;
        $option = array(
            'appid' => $_W['uniaccount']['key'],
            'secret' => $_W['uniaccount']['secret'],
        );
        $wxObj = new Wxadoc($option);
        $time = strtotime(date('Y-m-d', time()));
        $profit_subscribe_id = getConfig('profit_subscribe_id');

        $h = date('H');
        $i = date('i');
        $money_send_hour    = getConfig('earnings_send_hour');
        $money_send_minute  = getConfig('earnings_send_minute');

        $reward_type = getConfig('reward_type', 1);
        $dayCount = p_getcolumn('day', array('same_day' => $time - 86400, 'is_fictitious' => 1), 'sum(currency)');
        $content2 = array(
            'thing1' => array('value' =>"昨日打卡奖励已经发放啦"),
            'thing2' => array('value' =>"请点击进入我的页面查看"),
        );
        if (!p_get('system_day', array('same_day' => $time - 86400))) {
            $same_day =  $time - 86400;
            $virtualDayCount = p_getcolumn('day', array('same_day' => $time - 86400, 'is_fictitious' => 2), 'sum(currency)');
            $daySql = "SELECT COUNT(*) as total_number  FROM ". prefix('day'). " WHERE same_day = ". $same_day . " AND  clock > 0 AND uniacid =".UNIACID;
            $total_number = p_fetch($daySql);
            $systemDayData = array(
                'same_day'          => $time - 86400,
                'fictitious_currency' => $virtualDayCount,
                'fictitious_money' => $virtualDayCount * getConfig('currency_money'),
                'click_num'     => p_getcolumn('day', array('same_day' => $time - 86400), 'SUM(clock)'),
                'total_number'  => $total_number['total_number'],
                'created'       => time()
            );
            p_insert('system_day', $systemDayData);
        }

        if ($profit_subscribe_id && ($money_send_hour < $h || ($money_send_hour == $h && $money_send_minute <= $i))) {
            if ($sameDay = p_get('system_day', array('same_day' => $time - 86400))) {
                $systemDayData = array(
                    'currency'      => $dayCount,
                    'money'         => $reward_type == 1  ? $dayCount * getConfig('currency_money') : getConfig('pool'),
                );
                p_update('system_day', $systemDayData, array('id' => $sameDay['id']));
            }
            //$pool = getConfig('pool');
            //$currency_money = getConfig('currency_money');
            $rising = new  rising();

            while (true) {
              $syn = p_get('crontab_data', array('time' => $time - 86400));
                if (empty($syn)) {
                    $syn = array(
                        'day_id' => 0,
                        'time'   => $time - 86400
                    );
                    p_insert('crontab_data', $syn);
                    $syn['id'] = pdo_insertid();

                }
                $yesterday = $time - 86400 ;
                $sql = 'SELECT * FROM '.prefix('day').' WHERE id >' . $syn['day_id'] . ' AND status = 1 AND is_fictitious=1 AND same_day = '. $yesterday. ' AND uniacid= '.UNIACID.' ORDER bY id ASC LIMIT 10';
                $data = pdo_fetchall($sql);
                if (empty($data)) {
                    break;
                }
                foreach ($data as $value) {
                    $money = $this->getMoney($dayCount, $value['currency'], $reward_type);
                    $member = p_get('member', array('id' => $value['member_id'], 'is_block' => 1));
                    if (empty($member)) {
                        p_update('day',array('status' => 2, 'updated' => time()), array('id' => $value['id']));
                        continue;
                    }
                    $is_bonus = getConfig('is_bonus');
                    if ($is_bonus != 2) {
                        p_update('day',array('money' => $money,'status' => 2, 'updated' => time()), array('id' => $value['id']));
                    } else {
                        p_update('day',array('status' => 2, 'updated' => time()), array('id' => $value['id']));
                    }
                    if (!empty($member['openid'])) {
                        if($is_bonus !=2 ) {
                            $memberCount = p_getcolumn('day', array('same_day' => $yesterday, 'member_id' => $member['id']), 'clock');
                            if ($memberCount > getConfig('click_num_bonus')) {
                                $rising->change_money($member['id'], $money);
                            }
                            if (getConfig('is_bonus_deduction') == 2) {
                                $rising->change_currency($member['id'],  $value['currency'], 6, '分红扣出');
                            }
                        }
                        if ($member['remind'] > 0) {
                            $s = $wxObj->sendSubscribe($member['openid'], $profit_subscribe_id,'bh_rising/pages/index/index', $content2);
                            var_dump($s);
                            p_update('member', array('remind' => $member['remind'] - 1 ), array('id' => $member['id']));
                        }
                    }
                    $data = array(
                        'day_id' => $value['id'],
                        'time'   => $time
                    );
                    if (!p_update('crontab_data', $data, array('id' => $syn['id']))) {
                         die('修改失败');
                    }
                }
            }
        }
        json('success') ;
    }

    protected function getMoney($dayCount, $currency, $reward_type)
    {
        $pool = getConfig('pool');
        $currency_money = getConfig('currency_money');
        if ($reward_type == 2) {
            $money = round($pool / $dayCount , 4) * $currency;
        } else {
            $money = $currency * $currency_money;
        }
        return $money;
    }

    public function doPageBatch()
    {
        $member  = p_fetchall('SELECT * FROM '.prefix('member')." WHERE is_fictitious = 2 ORDER BY id DESC LIMIT 0, 1000");
        if ($member) {
            $time = strtotime(date('Y-m-d', time()));
            foreach ($member as $value) {
                if (!p_get('day', array('same_day' => $time, 'member_id' => $value['id']))) {
                    $currency = mt_rand(getConfig('batch_start_currency'), getConfig('batch_end_currency'));
                    $data = array(
                        'member_id' => $value['id'],
                        'same_day'  => $time,
                        'clock'     => mt_rand(1, 10),
                        'currency'  => $currency,
                        'is_fictitious' => 2,
                        'created'   => time()
                    );
                    if (p_insert('day', $data)) {
                        (new rising())->change_currency($value['id'], $currency,4, '虚拟产生');
                    }
                }
            }
        }

        json('success');

    }


    /**
     * 计划任务
     */
    public function doPageQQCrontab()
    {
        global $_W;
        $option = array(
            'appid' => $_W['uniaccount']['key'],
            'secret' => $_W['uniaccount']['secret'],
        );
        $wxObj = new Qqadoc($option);
        $time = strtotime(date('Y-m-d', time()));
        $profit_subscribe_id = getConfig('qq_profit_subscribe_id');

        $h = date('H');
        $i = date('i');
        $money_send_hour    = getConfig('qq_earnings_send_hour');
        $money_send_minute  = getConfig('qq_earnings_send_minute');

        $reward_type = getConfig('reward_type', 1);
        $dayCount = p_getcolumn('day', array('same_day' => $time - 86400, 'is_fictitious' => 1), 'sum(currency)');
        $content2 = array(
            'keyword1' => array('value' =>"昨日打卡奖励已经发放啦"),
            'keyword2' => array('value' =>"请点击进入我的页面查看"),
        );
        if (!p_get('system_day', array('same_day' => $time - 86400))) {
            $same_day =  $time - 86400;
            $virtualDayCount = p_getcolumn('day', array('same_day' => $time - 86400, 'is_fictitious' => 2), 'sum(currency)');
            $daySql = "SELECT COUNT(*) as total_number  FROM ". prefix('day'). " WHERE same_day = ". $same_day . " AND  clock > 0 AND uniacid =".UNIACID;
            $total_number = p_fetch($daySql);
            $systemDayData = array(
                'same_day'          => $time - 86400,
                'fictitious_currency' => $virtualDayCount,
                'fictitious_money' => $virtualDayCount * getConfig('currency_money'),
                'click_num'     => p_getcolumn('day', array('same_day' => $time - 86400), 'SUM(clock)'),
                'total_number'  => $total_number['total_number'],
                'created'       => time()
            );
            p_insert('system_day', $systemDayData);
        }

        if ($profit_subscribe_id && ($money_send_hour < $h || ($money_send_hour == $h && $money_send_minute <= $i))) {
            if ($sameDay = p_get('system_day', array('same_day' => $time - 86400))) {
                $systemDayData = array(
                    'currency'      => $dayCount,
                    'money'         => $reward_type == 1  ? $dayCount * getConfig('currency_money') : getConfig('pool'),
                );
                p_update('system_day', $systemDayData, array('id' => $sameDay['id']));
            }
            //$pool = getConfig('pool');
            //$currency_money = getConfig('currency_money');
            $rising = new  rising();

            while (true) {
                $syn = p_get('crontab_data', array('time' => $time - 86400));
                if (empty($syn)) {
                    $syn = array(
                        'day_id' => 0,
                        'time'   => $time - 86400
                    );
                    p_insert('crontab_data', $syn);
                    $syn['id'] = pdo_insertid();

                }
                $yesterday = $time - 86400 ;
                $sql = 'SELECT * FROM '.prefix('day').' WHERE id >' . $syn['day_id'] . ' AND status = 1 AND is_fictitious=1 AND same_day = '. $yesterday. ' AND uniacid= '.UNIACID.' ORDER bY id ASC LIMIT 10';
                $data = pdo_fetchall($sql);
                if (empty($data)) {
                    break;
                }
                foreach ($data as $value) {
                    $money = $this->getMoney($dayCount, $value['currency'], $reward_type);
                    $member = p_get('member', array('id' => $value['member_id']));
                    if (empty($member)) {
                        p_update('day',array('status' => 2, 'updated' => time()), array('id' => $value['id']));
                        continue;
                    }
                    $is_bonus = getConfig('is_bonus');
                    if ($is_bonus != 2) {
                        p_update('day',array('money' => $money,'status' => 2, 'updated' => time()), array('id' => $value['id']));
                    } else {
                        p_update('day',array('status' => 2, 'updated' => time()), array('id' => $value['id']));
                    }
                    if (!empty($member['openid'])) {
                        if($is_bonus !=2 ) {
                            $rising->change_money($member['id'], $money);
                        }
                        if ($member['remind'] > 0) {
                            $a = $wxObj->sendSubscribe($member['openid'], $profit_subscribe_id,'bh_rising/pages/index/index', $content2);
                            var_dump($a);
                            p_update('member', array('remind' => $member['remind'] - 1 ), array('id' => $member['id']));
                        }
                    }
                    $data = array(
                        'day_id' => $value['id'],
                        'time'   => $time
                    );
                    if (!p_update('crontab_data', $data, array('id' => $syn['id']))) {
                        die('修改失败');
                    }
                }
            }
        }
        json('success') ;

    }


    /**
     * 生成订单
     */
    public function doPageExchange()
    {
        $c = new bhCommon;

        $id = $c->get('id');
        if (empty($id)) {
            json('请先选择商品', 3);
        }

        $goods = p_get('goods', array('id' => $id, 'status' => 1, 'is_delete' => 1));

        if (empty($goods)) {
            $c->json('商品不存在或已下架', 3);
        }


        $volume = p_getcolumn('order', array('goods_id' => $id, 'is_pay' => 2), 'COUNT(*)') ? : 0;
        if ($volume >= $goods['inventory']) {
            $c->json('您来晚了,已经被兑换完了~', 3);
        }

        if ($goods['allow_number'] > 0) {
            if ($goods['allow_type'] == 1) {
                $buy_num = p_getcolumn('order', array('member_id' => $c->member['id'], 'goods_id' => $id, 'is_pay' => 2), 'COUNT(*)') ? : 0;
            } else {
                $t = strtotime(date('Y-m-d'));
                $sql = 'SELECT COUNT(*) FROM' . prefix('order') . " WHERE member_id={$c->member['id']} AND goods_id={$id} AND is_pay=2 AND created>={$t}";
                $buy_num = p_fetchcolumn($sql) ? : 0;
            }
            if ($buy_num >= $goods['allow_number']) {
                $c->json('每人最多兑换' . $goods['allow_number'] . '件~' , 3);
            }
        }

        if ($goods['exchange_number'] > $c->member['currency']) {
            $c->json('您的数量' . getConfig('currency_name') . '不足~', 3);
        }

        $address = p_get('address', array('member_id' => $c->member['id']));

        $insert = array(
            'goods_id' => $id,
            'member_id' => $c->member['id'],
            'exchange_type' => $goods['exchange_type'],
            'exchange_number' => $goods['exchange_number'],
            'type' => $goods['type'],
            'bag_money' => $goods['bag_money'],
            'money' => $goods['money'],
            'free' => $goods['free'],
            'address' => $address['address'],
            'name' => $address['name'],
            'phone' => $address['phone'],
            'is_pay' => 1,
            'created' => time()
        );

        pdo_begin();
        try{
            $money = 0;
            if ($goods['exchange_type'] == 2 && $goods['money'] > 0) {
                $money = $goods['money'];
            }
            if ($goods['is_free'] == 2 && $goods['free'] > 0) {
                $money += $goods['free'];
            }

            $exchange_type = getConfig('exchange_type');
            if ($money <= 0 || $exchange_type == 2) {

                if ($money > 0) {
                    if (!$c->rising->change_money($c->member['id'], $money, 5)) {
                        throw new Exception($c->rising->error);
                    }
                }

                $insert['is_pay'] = 2;
                if (!$c->rising->change_currency($c->member['id'], $goods['exchange_number'], 5)) {
                    throw new Exception($c->rising->error);
                }
                if ($goods['type'] == 2) {
                    if (!$c->rising->change_money($c->member['id'], $goods['bag_money'], 4)) {
                        throw new Exception($c->rising->error);
                    }
                    $insert['status'] = 3;
                    $insert['delivery_time'] = time();
                }
            }


            if ($goods['type'] == 3 && $c->rising->isPopularitye()) {
                $insert['is_under_line'] = $goods['is_under_line'];
                $insert['status'] = 3;
                $qq = $c->get('qq');
                if (empty($qq)) {
                    throw new Exception('请填写需要点赞的qq号');
                }
                jizan($qq, $goods['fabulous']);
            }


            if (!p_insert('order', $insert)) {
                throw new Exception('兑换失败,请稍后再试');
            }
            $o_id = pdo_insertid();
            if ($money > 0 && $exchange_type != 2) {
                $order_id = $c->rising->unifiedOrder($c->member['id'], $money, $o_id);
                if (!$order_id) {
                    throw new Exception('订单生成失败');
                }


                global $_W;
                $_W['openid'] = $c->member['openid'];
                $_W['member']['uid'] = $c->member['id'];

                if (isQq()) {
                    $notify_url  = $_W['siteroot'] . "app/index.php?i={$_W['uniacid']}&from=wxapp&c=entry&a=wxapp&do=qqCallBack&m=bh_cat";
                    $order  = array(
                        'mch_id'    => getConfig('qq_mch_id'),
                        'nonce_str' => $c->rising->out_trade_no(),
                        'body'      => getConfig('xcx_title').'-' .$goods['goods_name'],
                        'out_trade_no' => $order_id,
                        'fee_type'  => 'CNY',
                        'total_fee' => $money * 100,
                        'spbill_create_ip' => CLIENT_IP,
                        'trade_type' => 'JSAPI',
                        'notify_url' => $notify_url,
                    );
                    $order['sign'] = qqAutograph($order);
                    $s = http_post('https://qpay.qq.com/cgi-bin/pay/qpay_unified_order.cgi', $order);
                    libxml_disable_entity_loader(true);
                    $data = json_decode(json_encode(simplexml_load_string($s, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

                } else {
                    $order = array(
                        'tid' => $order_id, //订单号
                        'fee' => floatval($money), //支付参数
                        'title' => '礼品' . $goods['name'] //标题
                    );
                    $paydata = $this->pay($order);
                    if (is_error($paydata)) {
                        throw new Exception($paydata['message']);
                    }
                    $data = array('paydata' => $paydata);
                }

                pdo_commit();
                $c->json($data, 2);
            }

            pdo_commit();
            $c->json(array('order_id' => $o_id));
        } catch (Exception $e) {
            pdo_rollback();
            $c->json($e->getMessage(), 3);
        }
    }


    /**
     * 充值回调
     */
    public function payResult($data)
    {
        global $_GPC, $_W;
        $orderid = $data['tid'] ? $data['tid'] : $_GPC['orderid'];
        $paylog = pdo_get('core_paylog', array('uniacid' => $_W['uniacid'], 'module' => 'bh_rising', 'tid' => $orderid));

        $status = intval($paylog['status']) === 1;
        if (!$status) {
            exit;
        }

        $order = pdo_get('bh_zq_pay_order', array('trade_no' => $orderid));

        if (empty($order) || $order['status'] == 2) {
            exit;
        }

        $update = array(
            'transaction_id' => $paylog['encrypt_code'],
            'pay_time' => time(),
            'status' => 2
        );
        pdo_update('bh_ct_pay_order', $update, array('id' => $order['id']));
        //充值后续操作

        if ($order['type'] == 1) {
            $rising = new rising();
            $u = array('is_pay' => 2);
            if ($order['type'] == 2) {
                $u['status'] = 3;
                $rising->change_money($order['member_id'], $order['bag_money']);
            }
            $o = p_get('order', array('id' => $order['relation_id']));
            $goods = p_get('goods', array('id' => $o['goods_id']));
            $rising->change_currency($order['member_id'], $goods['exchange_number'], 5);
            if ($order['type'] == 3) {
                $rising->exchange_fictitious($order['member_id'], $goods['id']);
            }

            p_update('order', array('is_pay' => 2), array('id' => $order['relation_id']));


        }

        exit('ok');
    }


}